/*************************************************************************
 *
 * $Id: serial.h 60 2006-07-27 12:50:53Z alpov $
 * 
 *************************************************************************/         

#ifndef _SERIAL_H
#define _SERIAL_H

#define SerialSwitchTx()    PORTD |= _BV(PD2)
#define SerialSwitchRx()    PORTD &= ~_BV(PD2)

#define PACKET_PREFIX           0xaa

#define PACKET_DATA_LENGTH      64

#define PACKET_TX_BUF_SIZE      PACKET_DATA_LENGTH
#define PACKET_RX_BUF_SIZE      (PACKET_DATA_LENGTH - (sizeof(PACKET_HEADER) + sizeof(PACKET_FOOTER) + 3))
#define PACKET_TX_MAX_LENGTH    (PACKET_TX_BUF_SIZE - (sizeof(PACKET_HEADER) + sizeof(PACKET_FOOTER) + 3))
#define PACKET_RX_MAX_LENGTH    (PACKET_RX_BUF_SIZE + sizeof(PACKET_HEADER))

#define PACKET_RXTX_DELAY       5
#define PACKET_RX_TIMEOUT       200
#define PACKET_ACK_TIMEOUT      300     // PACKET_ACK_TIMEOUT > PACKET_RX_TIMEOUT !!!
#define PACKET_INIT_DELAY       500
#define PACKET_TX_TRIES         3


typedef union {
    struct {
        unsigned char seq;
        unsigned char dest;
        unsigned char src;
        unsigned char cmd;
        union {
            unsigned int item;
            struct {
                unsigned char item_hi;
                unsigned char item_lo;
            };
        };
    };
    unsigned char raw_data[0];
} PACKET_HEADER;


typedef union {
    unsigned int crc;
    unsigned char raw_data[0];
} PACKET_FOOTER;


#define ITEM_ALL                255

#define CMD_ACKNOWLEDGE         10
#define CMD_BOOTLOADER          20

#define CMD_DESC_WRITE          100
#define CMD_DESC_READ           101
 #define ITEM_SENSOR_COUNT      10
 #define ITEM_SENSOR_DESC       11
 #define ITEM_MODE_COUNT        20
 #define ITEM_MODE_DESC         21

#define CMD_STDATA_WRITE        110
#define CMD_STDATA_READ         111
 #define ITEM_TEMPERATURE       10
 #define ITEM_STATE             20
 #define ITEM_MESSAGE           100 // formalne patri pod STDATA, ale neni clenem struktury
//define ITEM_ALL               255

#define CMD_RWDATA_WRITE        120
#define CMD_RWDATA_READ         121
 #define ITEM_MODE              10
 #define ITEM_SHIFT             20
 #define ITEM_SWITCH            30
 #define ITEM_RTC               40
//define ITEM_ALL               255


#define ADDR_SERVER             0
#define ADDR_TERMINAL           (eedata.addr)
#define ADDR_BROADCAST          255

extern Mutex STDATA_Written, RWDATA_Written;

AVRX_EXTERNTASK(SerialTask);
extern void InitSerialTask(void);

extern void SerialSendAck(PACKET_HEADER *ph);
extern void SerialSendPacket(PACKET_HEADER *ph, char *data, unsigned char length, char gen_seq);

extern int SerialWaitAck(unsigned char seq);

extern void Serial_RWDATA_W(unsigned char item);
extern void Serial_RWDATA_R(void);
extern void Serial_STDATA_R(void);

#endif
